#include "client.h"

#ifndef SPLICE F MORE
#define SPLICE F MORE 0x04
#endif

int breakPoint_gets(int clientfd, train_t* pt){
    int ret = -1;
    int exit_flag = 1;

    printf("exit_flag:%d\n", exit_flag);

    char* filename = pt->buff;
    printf("filename:%s\n", filename);
    int filefd = open(filename, O_RDWR);
    if(filefd == -1){
        perror("open");
    }

    struct stat s;
    bzero(&s,sizeof(s));
    fstat(filefd, &s);

    int len_ed = s.st_size;

    ret = sendn(clientfd, &exit_flag, sizeof(exit_flag));
    ret = sendn(clientfd, &len_ed, sizeof(len_ed));

    int file_length = 0;
    ret = recvn(clientfd, &file_length, sizeof(file_length));

    printf("recvn:length:%d\n", file_length);
    printf("len_ed:%d\n",len_ed);

     if(file_length == len_ed){
        printf("file is exist.\n");
        return 0;
    }

    lseek(filefd, len_ed, SEEK_SET);

    //使用splice接收文件
    int breakfds[2];
    pipe(breakfds);

    int total = len_ed;
    while(total < file_length){
        ret = splice(clientfd, NULL, breakfds[1], NULL, 4096, SPLICE_F_MORE);
        total += ret;
        ret = splice(breakfds[0], NULL, filefd, NULL, 4096, SPLICE_F_MORE);
    }

    printf("recv success\n");

    close(filefd);
    close(breakfds[1]);
    close(breakfds[0]);
    return 0;
}

